from rest_framework import serializers
from goods.models import SKU


# 購物車序列化器
class CartSerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1,label="商品編號")
    count = serializers.IntegerField(min_value=1,max_value=200,label="商品數量")
    selected = serializers.BooleanField(default=True,required=False)

    # 多字段校驗
    def validate(self, attrs):
        # 獲取數據
        sku_id = attrs["sku_id"]
        count = attrs["count"]

        # 判斷商品是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            raise serializers.ValidationError("商品不存在")

        # 判斷count是否大於庫存
        if count > sku.stock:
            raise serializers.ValidationError("庫存不足")

        return attrs


# 刪除購物車序列化器
class CartDeleteSerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1, label="商品編號")

    # 單字段校驗
    def validate_sku_id(self, value):
        # 獲取sku_id對應的商品對象
        try:
            SKU.objects.get(id=value)
        except Exception as e:
            raise serializers.ValidationError("商品不存在")

        # 返回
        return value